<template>
	<view >
		<u-popup :show="value" @close="close" @open="open" round="18">
			<view class="choose-house-modal" >
				<!-- 顶部标题和关闭 -->
				<view class="modal-header">
					<text class="modal-title">请选择房屋</text>
          <view class="modal-header-close">
					<u-icon name="close" size="22" color="#999" @click="close"></u-icon>
          </view>
				</view>
				
				<!-- <view class="modal-search">
				    <u-search :showAction="false" bgColor="#F4F4F4" placeholder="请输入房屋进行搜索" 
					v-model="keyword"></u-search>
				</view> -->
				
				<view class="modal-tip">
				<view class="choose-house-warning choose-house-warning-tip">
        <u-image :src="warning" width="42rpx" height="42rpx"></u-image>
        <text class="choose-house-warning-text">
          {{ singleSelect ? '注：请选择一个房屋' : '注：若您有多套房，请全部选择后再点击确定' }}
        </text>
      </view>
				</view>
				<!-- 三栏联动 -->
				<view class="house-list-3col">
					<!-- 栋 -->
					<scroll-view scroll-y class=" house-col-left col-building">
						<view
             class="col-item-left"
							v-for="(building, bIdx) in leftBuildingList"
							:key="bIdx"
							:class="[
								'col-item',
								(bIdx === 0 && activeBuilding === -1) || (bIdx > 0 && activeBuilding === bIdx - 1) ? 'active' : '',
								building.isMyGroup ? 'my-col-item' : ''
							]"
							@click="selectBuilding(bIdx)"
						>
							<view v-if="(bIdx === 0 && activeBuilding === -1) || (bIdx > 0 && activeBuilding === bIdx - 1)" class="mine-border"></view>
							<text >{{ building.name }}</text>
							<view
								v-if="!building.isMyGroup && getSelectedCountByBuilding(building) > 0"
								class="mine-badge"
							>{{ getSelectedCountByBuilding(building) }}</view>
							<view
								v-if="building.isMyGroup && mySelectedRooms.length > 0"
								class="mine-badge"
							>{{ mySelectedRooms.length }}</view>
						</view>
					</scroll-view>
					<!-- 单元 -->
					<scroll-view scroll-y class="house-col col-unit">
						<view v-if="activeBuilding === -1">
							<view
								v-for="(item, idx) in mySelectedRooms"
								:key="idx"
								class="col-item my-group-item"
								style="display: flex; align-items: center;"
							>
								<!-- {{ item.room }} -->
								<text>{{ item.building }} {{ item.unit }} </text>
							</view>
							<view v-if="mySelectedRooms.length === 0" class="col-item my-group-item" style="color:#bbb;">暂无已选房屋</view>
						</view>
						<template v-else>
							<view
								v-for="(unit, uIdx) in (houseList[activeBuilding] && houseList[activeBuilding].childs ? houseList[activeBuilding].childs : [])"
								:key="uIdx"
								:class="['col-item', uIdx === activeUnit ? 'active' : '']"
								@click="selectUnit(uIdx)"
							>
								<text>{{ unit.name }}</text>
							</view>
						</template>
					</scroll-view>
					<!-- 房号 -->
					<scroll-view scroll-y class="house-col house-col2 col-room">
						<template v-if="activeBuilding !== -1">
							<view
								v-for="(room, rIdx) in safeRooms"
								:key="rIdx"
								class="col-item room-item"
              	@click="toggleRoom(safeBuildingName, safeUnitName, room.name, room.areaId)"
							>
								<text
									:class="['room-no', isChecked(safeBuildingName, safeUnitName, room.name, room.areaId) ? 'checked' : '', room.isMine ? 'mine-room' : '']"
								
								>
               
                {{ room.name }}</text>
                <view class="checkbox-room" >
								<u-checkbox
									:checked="isChecked(safeBuildingName, safeUnitName, room.name, room.areaId)"
									shape="square"
									activeColor="#3C75FA"
                
								/>
                <view class="checkbox-room-checked"></view>
                </view>
      
							</view>
						</template>
						<template v-else>
              <view v-if="activeBuilding === -1">
							<view
								v-for="(item, idx) in mySelectedRooms"
								:key="idx"
								class="col-item my-group-item"
								style="display: flex; align-items: center;"
							>
							
								<text>{{item.room }} </text>
							</view>
							<view v-if="mySelectedRooms.length === 0" class="col-item my-group-item" style="color:#bbb;">请先选择房屋</view>
						</view>
							
						</template>
					</scroll-view>
				</view>
				<!-- 底部按钮 -->
				<view class="modal-footer">
					<!-- <view class="modal-footer-share">
					  <u-icon name="share-square" color="#3C75FA" size="27px"></u-icon>
						<text class="modal-footer-share-text">分享</text>
					</view> -->
					<button
						class="modal-footer-btn"
						:class="{ 'modal-footer-btn-disabled': !selectedRooms.length }"
						:disabled="!selectedRooms.length"
            @click="handleConfirm"
					>
          确定
						
					</button>
				</view>
        <view class="app-bottom-paddig"></view>
			</view>
		</u-popup>
	</view>
</template>
<script>
import warning from '@/static/warning.svg'
import {getAreaQuery,getHouseList} from '@/api'
export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    communityId: {
      type: String,
      default: ''
    },
    // 是否单选模式，默认为false（多选）
    singleSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      warning,
      keyword: '',
      houseList: [
        
      ],
      activeBuilding: -1,
      activeUnit: 0,
      selectedRooms: []
    }
  },
  computed: {
    leftBuildingList() {
      return [{ name: '我的房屋', isMyGroup: true }].concat(this.houseList);
    },
    safeRooms() {
      if (this.activeBuilding < 0) return [];
      const b = this.houseList[this.activeBuilding];
      if (!b || !b.childs) return [];
      const u = b.childs[this.activeUnit];
      if (!u || !u.childs) return [];
      return u.childs;
    },
    safeBuildingName() {
      if (this.activeBuilding < 0) return '';
      const b = this.houseList[this.activeBuilding];
      return b ? b.name : '';
    },
    safeUnitName() {
      if (this.activeBuilding < 0) return '';
      const b = this.houseList[this.activeBuilding];
      if (!b || !b.childs) return '';
      const u = b.childs[this.activeUnit];
      return u ? (u.unitName || u.name) : '';
    },
    mySelectedRooms() {
      return this.selectedRooms.map(key => {
        const { areaId, building, unit, room, areaIdChain } = this.parseRoomKey(key);
        
        // 根据ID链的长度来确定各个ID
        let areaId_final = '';
        let buildingId = '';
        let unitId = '';
        let roomId = areaId; // 房号ID就是houseId
        
        if (areaIdChain && areaIdChain.length > 0) {
          if (areaIdChain.length >= 1) {
            areaId_final = areaIdChain[0]; // 区域ID
          }
          if (areaIdChain.length >= 2) {
            buildingId = areaIdChain[1]; // 楼栋ID
          }
          if (areaIdChain.length >= 3) {
            unitId = areaIdChain[2]; // 单元ID
          }
        }
        
        // 获取真正的房号信息、单元信息、楼栋信息和区域信息
        let roomCode = room; // 默认使用解析出的room
        let unitName = unit; // 默认使用解析出的unit
        let buildingName = building; // 默认使用解析出的building
        let areaName = ''; // 区域名称
        // 尝试从houseList中找到对应的房号信息、单元信息、楼栋信息和区域信息
        if (this.houseList && this.houseList.length > 0) {
          for (let buildingData of this.houseList) {
            if (buildingData.childs) {
              for (let unitData of buildingData.childs) {
                if (unitData.childs) {
                  for (let roomData of unitData.childs) {
                    if (roomData.areaId === areaId) {
                      roomCode = roomData.name; // 使用真正的房号
                      unitName = unitData.unitName || unitData.name; // 使用真正的单元名称
                      buildingName = unitData.buildingName || buildingData.name; // 使用真正的楼栋名称
                      areaName = buildingData.name; // 使用区域名称
                      break;
                    }
                  }
                }
              }
            }
          }
        }
        
        return {
          areaId: areaId_final,        // 区域ID
          areaName: areaName,          // 区域名称
          buildingId: buildingId,      // 楼栋ID
          unitId: unitId,              // 单元ID
          roomId: roomId,              // 房屋ID
          building: buildingName,      // 真正的楼栋名称
          unit: unitName,              // 真正的单元名称
          room: roomCode,              // 真正的房号名称
          roomCode: roomCode,          // 房号字段（新增）
          areaIdChain: areaIdChain     // 完整的ID链
        };
      });
    }
  },
  watch: {
    houseList(newList) {
      if (this.activeBuilding >= newList.length) {
        this.activeBuilding = -1;
        this.activeUnit = 0;
      }
      if (newList[this.activeBuilding]?.childs && this.activeUnit >= newList[this.activeBuilding].childs.length) {
        this.activeUnit = 0;
      }
    }
  },
  created() {
    this.getAreaQuery()
  },
  methods: {
    // 统一的 key 构造函数 - 包含完整的ID链信息
    generateRoomKey(areaId, building, unit, room, areaIdChain = []) {
      // 将ID链转换为字符串，用|分隔
      const idChainStr = areaIdChain.join('|');
      return `${areaId}-${building}-${unit}-${room}-${idChainStr}`;
    },
    // 统一的 key 解析函数 - 解析完整的ID链信息
    parseRoomKey(key) {
      const parts = key.split('-');
      const areaId = parts[0];
      
      // 从后往前解析，因为ID链在最后
      const idChainStr = parts[parts.length - 1]; // 最后一部分是ID链
      const areaIdChain = idChainStr ? idChainStr.split('|') : [];
      
      // 去掉areaId和idChainStr，剩下的部分按顺序是：building-unit-room
      const remainingParts = parts.slice(1, parts.length - 1);
      
      if (remainingParts.length >= 3) {
        // 有足够的部分，按顺序解析
        const building = remainingParts[0];
        const unit = remainingParts[1];
        const room = remainingParts[2];
        return { areaId, building, unit, room, areaIdChain };
      } else if (remainingParts.length === 2) {
        // 只有两部分，可能是building-room（没有unit）
        const building = remainingParts[0];
        const room = remainingParts[1];
        return { areaId, building, unit: '', room, areaIdChain };
      } else if (remainingParts.length === 1) {
        // 只有一部分，可能是building
        const building = remainingParts[0];
        return { areaId, building, unit: '', room: '', areaIdChain };
      } else {
        // 没有其他部分
        return { areaId, building: '', unit: '', room: '', areaIdChain };
      }
    },
    async getAreaQuery() {
      let data = await getAreaQuery({ communityId: this.communityId, pageNum: 1, pageSize: 1000, status: 1 });
      let areas = data.rows || [];

      // 处理新的数据结构：区域 -> 楼栋 -> 单元，将3级压成2级
      function flattenUnits(area, prefix = '', idChain = []) {
        let result = [];
        if (area.pmsBuilds && area.pmsBuilds.length > 0) {
          for (let build of area.pmsBuilds) {
            if (build.units && build.units.length > 0) {
              // 有单元，说明是3级结构
              for (let unit of build.units) {
                let newName = prefix ? (prefix + '-' + build.name + '-' + unit.name) : (build.name + '-' + unit.name);
                let newIdChain = idChain.concat([area.areaId, build.id, unit.id]);
                result.push({
                  areaId: unit.id,
                  name: newName,
                  buildingName: build.name, // 保存楼栋名称
                  unitName: unit.name,      // 保存单元名称
                  areaIdChain: newIdChain, // 保存完整链
                  level: 3, // 3级结构
                  queryId: unit.id // 查询时使用的ID
                });
              }
            } else {
              // 没有单元，说明是2级结构
              let newName = prefix ? (prefix + '-' + build.name) : build.name;
              let newIdChain = idChain.concat([area.areaId, build.id]);
              result.push({
                areaId: build.id,
                name: newName,
                areaIdChain: newIdChain, // 保存完整链
                level: 2, // 2级结构
                queryId: build.id // 查询时使用的ID
              });
            }
          }
        } else {
          // 没有楼栋，说明是1级结构，直接用区域ID查询
          result.push({
            areaId: area.areaId,
            name: area.name,
            areaIdChain: [area.areaId], // 保存完整链
            level: 1, // 1级结构
            queryId: area.areaId // 查询时使用的ID
          });
        }
        return result;
      }

      // 组装最终 houseList，将区域作为楼栋显示
      let houseList = areas.map(area => {
        return {
          areaId: area.areaId,
          name: area.name,
          childs: flattenUnits(area, '', [])
        };
      });

      this.houseList = houseList;
    },
    moveHandle(e){
      e.preventDefault();
      e.stopPropagation();
    },
    handleConfirm(){
     console.log("我触发了handleConfirm",this.mySelectedRooms)
     
      this.close();
    },
    open() {},
    close() {
      

      this.$emit('input', false)
      setTimeout(()=>{
        this.$emit("confirm",this.mySelectedRooms)
      },0)
    },
    async selectBuilding(idx) {
      if (idx === 0) {
        this.activeBuilding = -1; // "我的房屋"
        this.activeUnit = 0;
        return;
      } else {
        this.activeBuilding = idx - 1; // houseList 的下标
        this.activeUnit = 0;
        // 自动查第一个单元的房号
        const building = this.houseList[this.activeBuilding];
        if (building && building.childs && building.childs.length > 0) {
          const unit = building.childs[0];
          // 只在没有childs时查
          if (!unit.childs || unit.childs.length === 0) {
            // 根据层级决定传递的ID字段名
            let queryParams = {
              communityId: this.communityId,
              pageNum: 1,
              pageSize: 1000,
            };
            
            if (unit.level === 3) {
              queryParams.unitId = unit.queryId; // 3级结构传unitId
            } else if (unit.level === 2) {
              queryParams.buildId = unit.queryId; // 2级结构传buildId
            } else {
              queryParams.areaId = unit.queryId; // 1级结构传areaId
            }
            
            let data1 = await getHouseList(queryParams);
            unit.childs = (data1.rows || []).map(house => ({
              areaId: house.pmsHouse.houseId,
              // name: house.bankName
              name:house.pmsHouse.roomCode
            }));
            
            this.$set(building.childs, 0, { ...unit });
          }
        }
      }
    },
    async selectUnit(idx) {
      this.activeUnit = idx;
      const building = this.houseList[this.activeBuilding];
      const unit = building.childs[idx];
      
      // 根据层级决定传递的ID字段名
      let queryParams = {
        communityId: this.communityId,
        pageNum: 1,
        pageSize: 1000,
      };
      
      if (unit.level === 3) {
        queryParams.unitId = unit.queryId; // 3级结构传unitId
      } else if (unit.level === 2) {
        queryParams.buildId = unit.queryId; // 2级结构传buildId
      } else {
        queryParams.areaId = unit.queryId; // 1级结构传areaId
      }
      
      let data1 = await getHouseList(queryParams);
      unit.childs = (data1.rows || []).map(house => ({
         areaId: house.pmsHouse.houseId,
              // name: house.bankName
              name:house.pmsHouse.roomCode
      }));
      // 触发视图更新
      this.$set(this.houseList[this.activeBuilding].childs, idx, { ...unit });
    },
    isChecked(building, unit, room, areaId) {
      // 获取当前单元的ID链信息
      let areaIdChain = [];
      if (this.activeBuilding >= 0) {
        const buildingData = this.houseList[this.activeBuilding];
        if (buildingData && buildingData.childs && buildingData.childs[this.activeUnit]) {
          const unitData = buildingData.childs[this.activeUnit];
          areaIdChain = unitData.areaIdChain || [];
        }
      }
      
      const key = this.generateRoomKey(areaId, building, unit, room, areaIdChain);
      return this.selectedRooms.includes(key);
    },
    toggleRoom(building, unit, room, areaId) {
      // 获取当前单元的ID链信息
      let areaIdChain = [];
      if (this.activeBuilding >= 0) {
        const buildingData = this.houseList[this.activeBuilding];
        if (buildingData && buildingData.childs && buildingData.childs[this.activeUnit]) {
          const unitData = buildingData.childs[this.activeUnit];
          areaIdChain = unitData.areaIdChain || [];
        }
      }
      
      const key = this.generateRoomKey(areaId, building, unit, room, areaIdChain);
    
      const idx = this.selectedRooms.indexOf(key);
      if (idx > -1) {
        this.selectedRooms.splice(idx, 1);
       
      } else {
        // 如果是单选模式，先清空之前的选择
        if (this.singleSelect) {
          this.selectedRooms = [];
        }
        this.selectedRooms.push(key);
       
      }
    },
    getSelectedCountByBuilding(building) {
      if (!building || !building.childs) return 0;
      let count = 0;
      building.childs.forEach(unit => {
        if(unit.childs){
        unit.childs.forEach(room => {
          const key = this.generateRoomKey(room.areaId, building.name, unit.name, room.name, unit.areaIdChain);
          if (this.selectedRooms.includes(key)) {
            count++;
          }
        });
        }
      });
      return count;
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-house-modal {
  width: 100%;
	background: #fff;
	border-radius: 18rpx;
	padding: 29rpx 0 0rpx 0;
  height: 941rpx;
}
.modal-header {
  width: 100%;
	display: flex;
	justify-content: space-between;
	align-items: center;
  padding-right: 34rpx;
  justify-content: center;
  position: relative;
  color: rgba(51, 51, 51, 1);
   &-close{
      position: absolute;
      right: 30rpx;
     
    }
}
.modal-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #222;
}
.modal-search {
  margin-top: 29rpx;
	padding: 0rpx 30rpx  41rpx 30rpx ;
}
.modal-tip {
	display: flex;
	align-items: center;
	color: #FF9900;
	font-size: 24rpx;
  width: 100%;
  justify-content: center;
  padding:0 34rpx;
  display: flex;
  justify-content: flex-start;
}
.modal-tip-text {
	margin-left: 8rpx;
}
.house-list-3col {
  display: flex;
  width: 100%;
  height:673rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  margin: 0 0 0 0;
  box-sizing: border-box;
}
.house-col {
  flex: 2;
  overflow: hidden;
 
  height: 100%;
}
.house-col-left{
  width: 206rpx;
  height: 100%;
}
.col-building {
  border-top-left-radius: 16rpx;
  border-bottom-left-radius: 16rpx;
  background: #f5f7fa;
}
.col-unit {
  background: #fff;
}
.col-room {
  background: #fff;
  border-top-right-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
}
.col-item {
  height: 88rpx;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  font-size: 32rpx;
  color: #222;
  cursor: pointer;
  position: relative;
 
}
.col-item.active {
  background: #fff;
  color: $uni-color-primary;
  font-weight: 600;
  position: relative;
}
.col-item-left{
  display: flex;
  align-items: center;
  position: relative;
}
.mine-border {
  position: absolute;
  left: 0;
  height: 28rpx;
  width: 6rpx;
  background: $uni-color-primary;
  border-radius: 1998rpx 1998rpx 1998rpx 1998rpx;
}
.mine-badge {
  background: rgba(242, 74, 74, 1);
  color: #fff;
  font-size: 22rpx;
  border-radius: 50%;
  width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8rpx;
  position: absolute;
  right: 7rpx;
}
.room-item {
  justify-content: space-between;
}
.room-no {
  font-size: 30rpx;
  color: #222;
}
.room-no.checked {
  color: $uni-color-primary;
  font-weight: 600;
}
.mine-room {
  color: $uni-color-primary;
}
.modal-footer {
	display: flex;
	align-items: center;
	 box-shadow: 0 -2rpx 16rpx 0 rgba(0,0,0,0.1);
	justify-content: space-between;
  padding: 16rpx 40rpx 0 32rpx;
}
.modal-footer-share {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-right: 32rpx;
}
.modal-footer-share-text {
   font-weight: 400;
    font-size: 28rpx;
    color: #333333;
	margin-top: 8rpx;
}
.modal-footer-btn {
	flex: 1;
	height: 88rpx;
	background: $uni-color-primary;
	color: #fff;
	font-size: 32rpx;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 500;
	margin-left: 16rpx;
	border: none;
}
.modal-footer-btn-disabled {
  background: #E5E5EA !important;
  color: #999999 !important;
  border: none !important;
}
.choose-house-warning {
  color: #F9901B;
  font-size: 28rpx;
}
.choose-house-warning-tip {
  margin-bottom: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.choose-house-warning-text {
  margin-left: 8rpx;
}
.col-item {
  // width: 206rpx;
  width: 100%;
  height: 112rpx;
}
.my-col-item {
  font-weight: 600;
}
.my-group-item {
  font-size: 28rpx;
  color: #333;
  padding-left: 8rpx;
  white-space: nowrap;
}
.checkbox-room{
  width:24px;
  height: 20px;
  position: relative;

}
.checkbox-room-checked{
  width:24px;
  height: 20px;
  position: absolute;
  top: 0;
  left: 0;

}
.house-col2{
  flex: 2 !important;
  .col-item{
    width: 100%;
    justify-content: space-around;
  }
}
</style>
